<template>
  <div class="app-container">
    <el-row>
      <el-col :span="3" style="margin-right: 20px;">
        <el-input
          clearable
          size="medium"
          v-model="filterText"
          placeholder="关键词查询"
        />
        <div>
          <el-button plain type="primary" size="medium" class="expand-button" @click="handleCheckedTreeExpand">
            <div v-if="expandAll">
              <svg-icon icon-class="folder-open"/>
              全部折叠
            </div>
            <div v-else>
              <svg-icon icon-class="folder"/>
              全部展开
            </div>
          </el-button>
        </div>
      </el-col>
      <el-col :span="6">
        <el-tree
          :data="subjectList"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :indent="16"
          :default-expand-all="expandAll"
          ref="subjectTree"
          node-key="id"
        />
      </el-col>
      <el-col/>
    </el-row>
  </div>
</template>

<script>
import { subjectApi } from '@/api'

export default {
  data() {
    return {
      filterText: '', // 过滤文本
      subjectList: [], // 数据列表
      defaultProps: { // 自定义参数名
        id: 'id',
        children: 'children',
        label: 'title'
      },
      expandAll: false // 是否全部展开
    }
  },
  // 监听filterText的变化
  watch: {
    filterText(val) {
      this.$refs.subjectTree.filter(val) // 调用tree的filter方法
    }
  },
  created() {
    this.fetchNodeList()
  },
  methods: {
    // 获取数据
    fetchNodeList() {
      subjectApi.getTreeList().then(response => {
        this.subjectList = response.data.items
      })
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true
      return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },
    // 处理展开与折叠
    handleCheckedTreeExpand() {
      this.expandAll = !this.expandAll
      for (let i = 0; i < this.subjectList.length; i++) {
        this.$refs.subjectTree.store.nodesMap[this.subjectList[i].id].expanded = this.expandAll
        this.$refs.subjectTree.root.expanded = this.expandAll
      }
    }
  }
}
</script>

<style lang="scss">
.el-tree-node {
  .el-tree-node__label {
    font-size: 16px;
  }

  margin-top: 5px;
}

.expand-button {
  width: 100%;
  margin-top:10px;
}
</style>
